import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;


public class TresEnRaya extends JFrame{

	private JPanel contentPane;
	private JButton tBotones[][]=new JButton[3][3];
	private char tablero[][]=new char [3][3];
	private char jugador='O';
	private int contJugada=0;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					TresEnRaya frame = new TresEnRaya();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public TresEnRaya() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new GridLayout(3, 3));
		setContentPane(contentPane);
		char car='a';
		for(int i=0;i<3;i++){
			for(int j=0;j<3;j++){
				tBotones[i][j]=new JButton("");
				contentPane.add(tBotones[i][j]);
				tBotones[i][j].addActionListener(new btnOnClick());
				tablero[i][j]=car++;
			}
		}
		/*JButton btn1 = new JButton("");
		contentPane.add(btn1);
		btn9.addActionListener(new btnOnClick());*/
			
		
		
		}
	class btnOnClick implements ActionListener {
		  public void actionPerformed(ActionEvent e) {
			  for (int i=0;i<3;i++){
				  for (int j=0;j<3;j++){
					  if(tBotones[i][j]==e.getSource()){
						  tBotones[i][j].setText(Character.toString(jugador));
						  tablero[i][j]=jugador;
						  contJugada++;
						  comprobarGanador();
						  if (jugador=='O'){
							  jugador='X';
						  }else{
							jugador='O';	  
						  }
						  
				  }
			  }
			
		  }
		  }
		  private void comprobarGanador(){
			  //comprobar filas
			  for (int i=0;i<3;i++){
				  if ((tablero[i][0]==tablero[i][1])&& (tablero[i][1]==tablero[i][2])){
					  System.out.println("Ganador"+jugador);
					  return;
				  }
		  }
		  //comprobar columnas
		  for (int i=0;i<3;i++){
			  if ((tablero[0][i]==tablero[1][i])&& (tablero[1][i]==tablero[2][i])){
				  System.out.println("Ganador"+jugador);
				  return;
			  }
	  	  }
		  //comprobar diagonales
		  if (((tablero[0][0]==tablero[1][1])&& (tablero[1][1]==tablero[2][2]))||((tablero[0][2]==tablero[1][1])&& (tablero[1][1]==tablero[2][0]))){
			  System.out.println("Ganador"+jugador);
			  return;  
		  }

}
}
}